

""" Vertica.py,
    provide some utilities for vertica
"""

def getTypeString(type_id, precision, scale):
    typeDict = {
           -5 : "INT",
           1  : "CHAR(%d)" % precision,
           2  : "NUMERIC(%d,%d)" % (precision, scale),
           3  : "NUMERIC(%d,%d)" % (precision, scale),
           4  : "INT",
           5  : "INT",
           7  : "FLOAT",
           8  : "FLOAT",
           12 : "VARCHAR(%d)" % precision,
           91 : "DATE",
           93 : "TIMESTAMP(6)"
    }

    typeString = typeDict.get(type_id, "Unsupported Type(%d)" % type_id)

    return typeString


def createTable(resultset, schema, table):
    """rsmd is a ResultSetMetaData
    """

    rsmd = resultset.getMetaData()

    cmdlist = ["CREATE TABLE IF NOT EXISTS %s.%s(" % (schema, table)]

    for colindex in range(1, rsmd.columnCount+1):
        fieldstr = "    %s %s" % (rsmd.getColumnName(colindex),
                                  getTypeString(rsmd.getColumnType(colindex),
                                                rsmd.getPrecision(colindex),
                                                rsmd.getScale(colindex)))

        if rsmd.isAutoIncrement(colindex):
            fieldstr += " GENERATED BY DEFAULT AS IDENTITY"

        fieldstr += " DEFAULT NULL" if rsmd.isNullable(colindex) else " NOT NULL"

        if colindex != rsmd.columnCount:    fieldstr += ","

        cmdlist.append(fieldstr)

    cmdlist.append(");")
    cmdlist.append("CREATE PROJECTION IF NOT EXISTS" \
                  + " %s.prj_%s as SELECT * from %s.%s;" % (schema,
                                      table, schema, table))

    return "\n".join(cmdlist)






